package com.hd.trans.utils;


import com.hd.trans.network.HeaderInterceptor;
import com.hd.trans.network.apiService.UrlConstant;
import com.hd.trans.network.download.DownloadService;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: yang
 * Date: 2018/11/14 11:03
 * Desc: 下载工具类
 */
public class DownloadUtils {

    private static final String TAG = "DownloadUtils";


    private final static long CONNECT_TIMEOUT = 30L;
    private final static long READ_TIMEOUT = 30L;
    private final static long WRITE_TIMEOUT = 30L;

    private Retrofit retrofit;

    private DownloadService downloadService;

//    private Disposable mDisposable;


    private static class SingletonHolder {
        private static final DownloadUtils INSTANCE = new DownloadUtils();
    }


    /**
     * 获取DownloadUtils
     *
     * @return
     */
    public static DownloadUtils getInstance() {

        return SingletonHolder.INSTANCE;
    }


    private DownloadUtils() {
        init();
    }

    /**
     * 获取httpService
     */
    public DownloadService getDownloadService() {
        return downloadService;
    }

    private void init() {

        //声明日志类
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        //设定日志级别
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new HeaderInterceptor(false))
                .retryOnConnectionFailure(true)
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .client(httpClient)
                .baseUrl(UrlConstant.getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())//json转换成JavaBean
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();


        downloadService = retrofit.create(DownloadService.class);

    }


}
